<template>
  <div>
    <button @click="goBack" class="back-button">返回上一页</button>

    <div class="container">
      <div class="column">
        <div class="input-group">
          <label for="frameCount">捕获的帧的数量:</label>
          <input type="text" id="frameCount" v-model="frameCount">
        </div>
        <div class="input-group">
          <label for="captureCondition">捕获的条件:</label>
          <input type="text" id="captureCondition" v-model="captureCondition">
        </div>
      </div>

      <div class="column">
        <div class="button-group">
          <button class="action-button start" @click="start">开始捕获</button>
          <button class="action-button clear" @click="clearData">清空数据</button>
          <button class="action-button stop" @click="stop">停止捕获</button>
        </div>
      </div>
    </div>

    <!-- 添加消息提示框 -->
    <div v-if="message" :class="['message', message.type]">
      {{ message.text }}
    </div>

    <!-- 添加数据展示列表 -->
    <div class="data-list-container">
      <h3>捕获的数据 (总计: {{ packetCount }})</h3>
      <div class="data-list">
        <div v-for="(item, index) in dataList" :key="index" class="data-item">
          <span class="data-content">{{ item }}</span>
          <button class="view-button" @click="viewData(index)">查看</button>
        </div>
        <div v-if="dataList.length === 0" class="no-data">
          暂无数据
        </div>
      </div>
    </div>

    <!-- 数据包详情显示框 -->
    <div v-if="showPacketDetails" class="packet-details-container">
      <div class="details-header">
        <h3>数据包详情</h3>
        <button class="close-button" @click="showPacketDetails = false">关闭</button>
      </div>
      <div class="details-content">
        <div v-if="showPacketDetails">
          <div class="protocol-section" v-for="(packet, index) in selectedPacketDetails" :key="index">
            <h4>{{ packet.net_type }}</h4>
            <div class="packet-details" v-for="(item, index) in packet.details" :key="index">
              <span>{{ item }}</span>
            </div>
          </div>
        </div>
        <div v-else class="no-details">
          没有可用的详情数据
        </div>
      </div>
    </div>

    <!-- 十六进制展示表 -->
    <div v-if="showPacketDetails" class="packet-details-container">
      <div class="details-header">
        <h3>十六进制展示表</h3>
        <button class="close-button" @click="showPacketDetails = false">关闭</button>
      </div>
      <div class="details-content">
        <div v-if="showPacketDetails">
          <div class="hex-line" v-for="(hex_line, index) in hexTable" :key="index">
            <span class="address">{{ hex_line[0] }}:</span>
            <span class="hex-data">{{ hex_line[1] }}</span>
            <span class="ascii-data">{{ hex_line[2] }}</span>
          </div>
        </div>
        <div v-else class="no-details">
          没有可用的十六进制数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

const frameCount = ref('');
const captureCondition = ref('');
const dataList = ref<string[]>([]);
const packetCount = ref(0);
let refreshInterval: number | null = null;
// 添加消息提示相关的响应式变量
const message = ref<{ type: string; text: string } | null>(null);
// 用于存储选中的数据包详情
const selectedPacketDetails = ref(null);
// 控制详情框的显示/隐藏
const showPacketDetails = ref(false);
//添加十六进制表展示情况
const hexTable = ref(null);

// 添加显示消息的函数
function showMessage(text: string, type: string = 'info') {
  message.value = { type, text };
  // 3秒后自动隐藏消息
  setTimeout(() => {
    message.value = null;
  }, 3000);
}

function goBack() {
  window.history.back();
}

function start() {
  //弹出报文捕获的窗口
  const result = confirm('是否开始报文捕获？');
  if (result) {
    // 用户点击"是"
    sendCapture();
  } else {
    // 用户点击"否"或"取消"
    console.log('用户取消了捕获操作');
  }
}

async function sendCapture() {
  // 发送数据到后端
  const data = {
    frameCount: frameCount.value,
    captureCondition: captureCondition.value
  };

  try {
    const response = await fetch('/api/capture', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    });

    if (response.ok) {
      console.log('数据发送成功');
      showMessage('开始捕获成功', 'success');
      // 开始定期刷新数据
      startDataRefresh();
    } else {
      console.error('发送数据失败:', response.status);
      showMessage('发送数据失败: ' + response.status, 'error');
    }
  } catch (error) {
    console.error('发送数据时出错:', error);
    showMessage('发送数据时出错，请检查后端服务是否启动', 'error');
  }
}


//清空数据
async function clearData() {
  try {
    const response = await fetch('/api/clear_data', { method: 'POST' })
    if (response.ok) {
      console.log('数据清理成功');
      dataList.value = [];
      packetCount.value = 0;
      showMessage('数据清理成功', 'success');
    }
    else {
      console.error('数据清理失败:', response.status);
      showMessage('数据清理失败: ' + response.status, 'error');
    }
  } catch (error) {
    console.error('数据清理时出错:', error);
    showMessage('数据清理时出错，请检查后端服务是否启动', 'error');
  }
}

//停止捕获
async function stop() {
  try {
    const response = await fetch('/api/stop_capture', { method: 'POST' })
    if (response.ok) {
      console.log('停止捕获成功');
      // 停止定期刷新数据
      stopDataRefresh();
      showMessage('停止捕获成功', 'success');
    }
    else {
      console.error('停止捕获失败:', response.status);
      showMessage('停止捕获失败: ' + response.status, 'error');
    }
  } catch (error) {
    console.error('停止捕获时出错:', error);
    showMessage('停止捕获时出错，请检查后端服务是否启动', 'error');
  }
}

// 获取当前数据
async function fetchCurrentData() {
  try {
    const response = await fetch('/api/current_data');
    if (response.ok) {
      const result = await response.json();
      dataList.value = result.data || [];
      packetCount.value = result.packet_count || 0;
    } else {
      console.error('获取数据失败:', response.status);
      showMessage('获取数据失败: ' + response.status, 'error');
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
    showMessage('获取数据时出错，请检查后端服务是否启动', 'error');
  }
}

//查看某一个数据的信息
async function viewData(index: number) {
  // 传递到后端，后端会寻找我们查看的对象
  const data = {
    index: index
  };
  try {
    const response = await fetch('api/view_data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    });
    if (response.ok) {
      const result = await response.json();
      console.log('Packet details:', result.data);
      console.log('Hex table:', result.hex_dump);
      selectedPacketDetails.value = result.data;
      showPacketDetails.value = true;
      hexTable.value = result.hex_dump;
      showMessage('查看数据成功', 'success');
    } else {
      console.error('查看数据失败:', response.status);
      showMessage('查看数据失败: ' + response.status, 'error');
    }
  } catch (error) {
    console.error('查看数据时出错:', error);
    showMessage('查看数据时出错，请检查后端服务是否启动', 'error');
  }
}

// 开始定期刷新数据
function startDataRefresh() {
  // 立即获取一次数据
  fetchCurrentData();
  // 每秒刷新一次数据
  refreshInterval = window.setInterval(fetchCurrentData, 1000);
}

// 停止定期刷新数据
function stopDataRefresh() {
  if (refreshInterval) {
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
}

// 组件挂载时开始获取数据
onMounted(() => {
  // 页面加载时获取一次当前数据
  fetchCurrentData();
});

// 组件卸载前清理定时器
onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval);
  }
});
</script>


<style scoped>
.back-button {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 10px 20px;
  font-size: 16px;
  background-color: green;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.container {
  display: flex;
  margin-top: 30px;
}

.column {
  flex: 1;
  padding: 100px;
}

.input-group {
  margin-bottom: 40px;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 24px;
}

.input-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-button {
  padding: 20px 80px;
  font-size: 24px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.start {
  background-color: #4CAF50;
  color: white;
}

.clear {
  background-color: #f44336;
  color: white;
}

.stop {
  background-color: #ff9800;
  color: white;
}

.data-list-container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.data-list-container h3 {
  margin-top: 0;
}

.data-list {
  max-height: 400px;
  overflow-y: auto;
  min-height: 50px;
}

.data-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  font-family: monospace;
  word-break: break-all;
}

.data-item:last-child {
  border-bottom: none;
}

.no-data {
  padding: 20px;
  text-align: center;
  color: #999;
}

.data-content {
  flex: 1;
}

.view-button {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.view-button:hover {
  background-color: #0056b3;
}

.packet-details-container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.close-button {
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.close-button:hover {
  background-color: #5a6268;
}

.details-content {
  max-height: 400px;
  overflow-y: auto;
}

.packet-details {
  text-align: left;
  padding-left: 10px;
  white-space: pre-wrap;
}

.no-details {
  padding: 20px;
  text-align: center;
  color: #999;
}

.hex-dump-container {
  font-family: monospace;
  line-height: 1.5;
}

.hex-line {
  display: flex;
}

.address {
  width: 50px;
  color: #666;
}

.hex-data {
  width: 350px;
  font-family: monospace;
  text-align: left;
}

.ascii-data {
  margin-left: 10px;
  color: #006600;
}
</style>